package com.atguigu.gulimallssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;
    @ResponseBody
@GetMapping("/userInfo")
    public String userInfo(@RequestParam("token")String token){
    String username = redisTemplate.opsForValue().get(token);
    return username;
    }





    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token", required = false) String sso_token) {
        model.addAttribute("url", url);
        if (!StringUtils.isEmpty(sso_token)) {
            //有人登录过
            return "redirect:" + url + "?token=" + sso_token;
        } else {
            return "login";
        }


    }
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {
          if (!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password)){
             //保存登录成功的用户
              String uuid = UUID.randomUUID().toString().replace("-", "");
              redisTemplate.opsForValue().set(uuid,username);
              Cookie sso_token=new Cookie("sso_token",uuid);
              response.addCookie(sso_token);
              //登录成功，跳回之前页面
              return "redirect:"+url+"?token="+uuid;
          }else{
              //跳回到之前的登录页面
              return "login";
          }



    }



}


















